<template>
  <div>
    <div class="top flexBetweenCenter">
      <div>
        <a-button icon="left" class="rigntMargin" @click="leftMonth" />
        <span class="monthPicker">
          <a-month-picker
            v-model="monthTime"
            format="YYYY年MM月"
            class="rigntMargin"
            @change="onChange"
          />

          <a-button icon="right" class="rigntMargin" @click="rightMonth" />
        </span>

        <a-select
          placeholder="请选择"
          style="width:300px;margin-right:20px"
          @change="handleChange"
          :allowClear='true'
        >
          <a-select-opt-group :label="item.label" v-for="(item) in teamGroup" :key="item.key">
            <a-select-option
              v-for="(data) in item.children "
              :key="data.key"
              :value="data.key"
            >{{data.label}}</a-select-option>
          </a-select-opt-group>
        </a-select>
        <!-- <a-cascader
            :options="options"
            :display-render="displayRender"
            expand-trigger="hover"
            placeholder="Please select"
            :default-value="['江苏路通建筑劳务有限公司', '下构一队', '钢筋班']"
            @change="onChange"
            style="margin-right:10px"
        />-->

        <a-button style="font-size:16px" class="rigntMargin" @click="exportTable">
          <span style="display:inline-block;hight:32px"></span>导出
        </a-button>
      </div>
      <div>
        <a-input-search
          placeholder="请输入姓名"
          v-model="fullName"
          style="width: 300px"
          @search="onSearch"
        />
      </div>
    </div>
    <a-spin :spinning="spinning">
      <div class="atable">
        <a-table :data-source="data" :scroll="{ x: 600}" :pagination="false">
          <a-table-column key="date" title="月份" data-index="date" width="150px" align="center" fixed='left'/>
          <a-table-column
            key="obj"
            title="姓名"
            data-index="obj"
            width="150px"
            align="center"
            fixed='left'
          >
            <template slot-scope="text">
              <a @click="routeDetail(text)">{{text.fullName}}</a>
            </template>
          </a-table-column>
          <a-table-column
            key="postName"
            title="岗位"
            data-index="postName"
            width="150px"
            align="center"
            fixed='left'
          />
          <a-table-column
            key="attendanceDay"
            title="出勤天数"
            data-index="attendanceDay"
            width="120px"
            align="center"
            fixed='left'
          />
          <a-table-column
            :key="index.toString()"
            :data-index="index.toString()"
            v-for="index in this.dayNum"
            width="100px"
            align="center"
          >
            <!-- <span slot="title" :class="{ restDay: (moment(this.monthData+index).subtract(weekOfday - 6, 'days').format('YYYY-MM-DD')!='Saturday ')||(moment(this.monthData+index).subtract(weekOfday - 6, 'days').format('YYYY-MM-DD')!='Sunday ') }">{{index}}</span> -->
            <span slot="title" :class="{ restDay:isworkDay(index)}">{{index}}</span>
            <template slot-scope="text">
              <!-- //打卡 -->
              <img :src="kaoqin2" alt v-if="(text=='1')||(text=='3')" />
              <!-- //未打卡 -->
              <img :src="kaoqin1" alt v-else />
            </template>
          </a-table-column>
        </a-table>
      </div>
      <!-- 分页 -->
      <div class="pagination flexBetween">
        <div>共 {{total}} 条记录 第 {{current}} / {{this.configFun.pageNum(Math.ceil((total/pageSize)))}} 页</div>
        <div>
          <a-pagination
            :current="current"
            :page-size-options="pageSizeOptions"
            :total="this.configFun.pageNum(total)"
            show-size-changer
            :page-size="pageSize"
            @showSizeChange="onShowSizeChange"
            @change="pageChange"
            show-quick-jumper
          >
            <template slot="buildOptionText" slot-scope="props">
              <span>{{ props.value }}条/页</span>
              <!-- <span v-if="props.value === '40'">全部</span> -->
            </template>
          </a-pagination>
        </div>
      </div>
    </a-spin>
  </div>
</template>

<script>
import moment from 'moment'
import kaoqin1 from '@/assets/img/kaoqin11.png'
import kaoqin2 from '@/assets/img/kaoqin2.png'
import { monthAttendance } from '@/api/attendance'
import { mapGetters } from 'vuex'
import { unitTeamQuery } from '@/api/laborUnitTeam'

const options = [
  {
    value: '江苏路通建筑劳务有限公司',
    label: '江苏路通建筑劳务有限公司',
    children: [
      {
        value: '下构一队',
        label: '下构一队',
        children: [
          {
            value: '钢筋班',
            label: '钢筋班'
          }
        ]
      }
    ]
  },
  {
    value: '南京仁泰基础工程有限公司',
    label: '南京仁泰基础工程有限公司',
    children: [
      {
        value: '路基施工一队',
        label: '路基施工一队',
        children: [
          {
            value: '混凝土班组',
            label: '混凝土班组'
          }
        ]
      }
    ]
  }
]
export default {
  data() {
    return {
      monthTime: moment(new Date(), 'YYYY年MM月'),
      data: [],
      kaoqin1,
      kaoqin2,
      pageSizeOptions: ['5', '10', '20', '30', '40'],
      current: 1,
      pageSize: 10,
      total: 1,
      // defaultData: '',
      teamGroup: [],
      options,
      fullName: '',
      monthData: '',
      dayNum: 30,
      teamId:'',
      spinning: false,
      flag: false
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    this.getTree()
  },
  mounted() {
    // console.log(this.monthTime)
    this.monthData = moment(this.monthTime).format('YYYY-MM')
  },
  watch: {
    monthData(val, oldval) {
      // console.log(val);
      this.dayNum = moment(val, 'YYYY-MM').daysInMonth()
    }
  },

  methods: {
    moment,
    isworkDay(res) {
      // let data = this.monthData + res
      let nowork = []
      nowork = this.getWeekend()
      // console.log(nowork)
      return nowork.includes(res)
    },
    getWeekend() {
      let week = [],
        td,
        day,
        d
      for (let i = 1; i <= this.dayNum; i++) {
        td = new Date(this.monthData + '/' + i)
        day = td.getDay()
        d = td.getDate()
        if (!isNaN(day)) {
          if (day == 0 || day == 6) {
            week.push(d)
          }
        }
      }
      return week
    },

//搜索时获取满足的有多少页
    getTotal(val, current) {
      let size = ''
      let page = ''
      if (val) {
        size = val
      } else {
        size = this.pageSize
      }
      if (current) {
        page = current
      } else {
        page = this.current
      }
      let data = {
        date: this.monthData,
        likeFullName: this.fullName,
        orgId: this.userInfo.orgId,
        projectId: this.userInfo.projectId,
        teamId: this.teamId,
        page: this.current,
        size: this.pageSize,
        typeCode: '2'
      }
     
      monthAttendance(data)
        .then((res) => {
        let data = res.data
        this.total = data.total
        //   console.log(Math.ceil(this.total/size));
        // console.log(page);
        if (Math.ceil(this.total / size) < page) {
          this.current = 1
        } else {
          this.current = page
        }

        this.pageSize = size
        this.getMonth()
      })
    },

    getMonth() {
      let data = {
        date: this.monthData,
        likeFullName: this.fullName,
        orgId: this.userInfo.orgId,
        projectId: this.userInfo.projectId,
        teamId: this.teamId,
        page: this.current,
        size: this.pageSize,
        typeCode: '2'
      }
      this.spinning = true
      monthAttendance(data)
        .then((res) => {
          let data = res.data.data
          data.forEach((item) => {
            item.key = item.id
            item['list'] = []
            item.lists.forEach((listItem, index) => {
              let order = index + 1
              // let obj={}
              // obj[order]=listItem
              // item['list'].push(obj)
              item[order] = listItem
            })
            item['obj']={fullName:item.fullName,id:item.id}
          })
          this.data = data
          this.total = res.data.total
          this.spinning = false
          // console.log(this.data)
        })
        .catch((res) => {
          this.spinning = false
        })
    },
    onChange(value) {
      this.current=1
      this.monthData = moment(this.monthTime).format('YYYY-MM')
      this.getMonth()
    },
    displayRender({ labels }) {
      return labels[labels.length - 1]
    },
    routeDetail(text) {
      // console.log(id);
      
      const { href } = this.$router.resolve({
        path: `/personnelInformationLabor/${text.id}`,
        query: { id: text.id }
      })

      window.open(href, '_blank')
    },
    onSearch(value) {
      // console.log(value)
      this.getTotal()
    },
    leftMonth() {
      this.current = 1
      this.monthTime = moment(this.getLastMonth(this.monthTime._d), 'YYYY年MM月')
      this.monthData = moment(this.monthTime).format('YYYY-MM')
      this.getMonth()
    },
    rightMonth() {
      this.current = 1
      this.monthTime = moment(this.getNextMonth(this.monthTime._d), 'YYYY年MM月')
      this.monthData = moment(this.monthTime).format('YYYY-MM')
      // this.dayNum=27
      this.getMonth()
    },
    getLastMonth(date) {
      //获取上个月日期
      var year = date.getFullYear()
      var month = date.getMonth()
      if (month == 0) {
        year = year - 1
        month = 12
      }
      return year + '年' + month + '月'
    },
    getNextMonth(date) {
      var year = date.getFullYear()
      var month = date.getMonth() + 2
      if (month == 13) {
        year = year + 1
        month = 1
      }
      return year + '年' + month + '月'
    },
    handleChange(value) {
      this.current = 1
      this.teamId = value
      // console.log(value)
      this.getMonth()
    },
    onShowSizeChange(current, pageSize) {
      // console.log(current, pageSize)
      this.current = 1
      this.pageSize = pageSize
     this.getTotal(pageSize, this.current)
    },
    pageChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
     this.getTotal(pageSize, this.current)
    },
    getTree() {
      unitTeamQuery().then((res) => {
        let data = res.data.data
        let childrenFlag = false
        data.forEach((item) => {
          item.key = item.labourOrgId
          item.label = item.labourOrgName
          item.children = []
          if (item.teamVOList.length > 0) {
            item.children = []
            item.teamVOList.forEach((res) => {
              res.key = res.id
              res.label = res.name
            })
            item.children = item.teamVOList
          }

          // if (childrenFlag == false && item.teamVOList.length > 0) {
          //   // console.log(item);

          //   this.defaultData = item.teamVOList[0].name
          //   this.flag = true
          //   childrenFlag = true
          //   this.teamId = item.teamVOList[0].id
          // }
        })
        // if (data[0].children.length > 0) {
        //   this.defaultData = data[0].children[0].label
        //   this.flag = true
        //   this.teamId = data[0].children[0].key
        // } else {
        //   this.defaultData = ''
        //   this.teamId = ''
        // }
        // console.log(data)

        this.teamGroup = data
        this.getMonth()
        // console.log(this.defaultSelectedKey[0])

        // console.log( this.treeData );
      })
    },
    exportTable() {
      let data = {
        date: this.monthData,
        likeFullName: this.fullName,
        // orgId: this.userInfo.orgId,
        // projectId: this.userInfo.projectId,
        teamId: this.teamId,
        // page: this.current,
        // size: this.pageSize,
        typeCode: '2'
      }
      window.open(
        process.env.VUE_APP_BASE_API +
          '/v1/orgPerson/clock/month/export?teamId=' +
          this.teamId +
          '&typeCode=' +
          '2' +
          '&likeFullName=' +
          this.fullName +
          '&date=' +
          this.monthData,
        '_blank'
      )

      this.$message.success('导出成功')
    }
  }
}
</script>

<style scoped>
::v-deep .ant-calendar-picker-icon {
  display: none;
}
::v-deep .ant-calendar-picker-clear {
  display: none;
}

.monthPicker ::v-deep .ant-calendar-picker-input.ant-input {
  line-height: 1.5;
  background: #1890ff;
  text-align: center;
  color: #fff;
  width: 120px;
  border: 1px solid #1890ff;
  cursor: pointer;
}
.rigntMargin {
  margin-right: 20px;
}
.restDay {
  color: #ff9933;
}
.top {
  padding-top: 30px;
  margin-bottom: 30px;
}
.atable {
  margin-bottom: 20px;
}
::v-deep .ant-table-tbody>tr>td, .ant-table-thead>tr>th {
  height: 55.5px;
}
</style>